import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tech_shop/src/cart_controller.dart';
import 'package:flutter_tech_shop/src/context_extension.dart';
import 'package:flutter_tech_shop/src/screens/message_page.dart';
import 'package:flutter_tech_shop/src/screens/product_detail.dart';
import 'package:flutter_tech_shop/src/screens/search_page.dart';
import 'package:flutter_tech_shop/src/widgets/input_field.dart';
import 'package:get/get.dart';

import '../shared/Product.dart';
import '../shared/colors.dart';
import '../shared/fryo_icons.dart';
import '../shared/partials.dart';
import '../shared/products_model.dart';
import '../shared/styles.dart';
import 'product_page.dart';

class StorePage extends StatefulWidget {
  const StorePage({super.key});

  @override
  State<StorePage> createState() => _StorePageState();
}

class _StorePageState extends State<StorePage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: bgColor,
      drawer: drawer(),
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            _scaffoldKey.currentState?.openDrawer();
          },
          iconSize: 21,
          icon: Icon(Fryo.funnel),
        ),
        backgroundColor: primaryColor,
        title: const Text('XJn',
            style: logoWhiteStyle, textAlign: TextAlign.center),
        actions: <Widget>[
          IconButton(
            padding: EdgeInsets.all(0),
            onPressed: () {
              context.push(const SearchPage());
            },
            iconSize: 21,
            icon: Icon(Fryo.magnifier),
          ),
          IconButton(
            padding: EdgeInsets.all(0),
            onPressed: () {
              context.push(const MessagePage());
            },
            iconSize: 21,
            icon: Icon(Fryo.alarm),
          )
        ],
      ),
      body: storeTab(context),
    );
  }

  Widget drawer() {
    return Drawer(
      child: SafeArea(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: const Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 20),
              Text(
                '价格筛选',
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(height: 20),
              Row(
                children: [
                  SizedBox(
                    width: 100,
                    height: 50,
                    child: InputField(borderRadius: 10, hintText: '2000'),
                  ),
                  SizedBox(width: 10),
                  Text(
                    '-',
                    style: TextStyle(fontSize: 24),
                  ),
                  SizedBox(width: 10),
                  SizedBox(
                    width: 100,
                    height: 50,
                    child: InputField(
                      borderRadius: 10,
                      hintText: '8000',
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget storeTab(BuildContext context) {
    // will pick it up from here
    // am to start another template
    List<Product> hotProducts = products;

    List<Product> disCount = products;

    return ListView(children: <Widget>[
      /// 头部分类
      headerTopCategories(),

      deals(
        '热卖',
        onViewMore: () {},
        items: List.generate(
          hotProducts.length,
          (index) => productItem(
            hotProducts[index],
            onTapped: () {
              context.push(
                ProductDetail(
                  product: hotProducts[index],
                ),
              );
            },
            imgWidth: 250,
            onLike: () {
              final cartController = Get.find<CartController>();
              setState(() {
                products[index].userLiked = !products[index].userLiked;
                if (products[index].userLiked) {
                  cartController.addFavorite(products[index]);
                } else {
                  cartController.removeFavorite(products[index]);
                }
                debugPrint('${products[index].name} ${products[index].userLiked}');
              });
            },
          ),
        ),
      ),

      deals(
        '历史低价',
        onViewMore: () {},
        items: List.generate(
          disCount.length,
          (index) => productItem(
            disCount[index],
            onTapped: () {
              context.push(
                ProductDetail(
                  product: hotProducts[index],
                ),
              );
            },
            imgWidth: 250,
            onLike: () {},
          ),
        ),
      ),
    ]);
  }

  Widget sectionHeader(String headerTitle, {onViewMore}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          margin: const EdgeInsets.only(left: 15, top: 10),
          child: Text(headerTitle, style: h4),
        ),
        Container(
          margin: const EdgeInsets.only(left: 15, top: 2),
          child: TextButton(
            onPressed: onViewMore,
            child: const Text('更多 ›', style: contrastText),
          ),
        )
      ],
    );
  }

// wrap the horizontal listview inside a sizedBox..
  Widget headerTopCategories() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        sectionHeader('所有分类', onViewMore: () {}),
        SizedBox(
          height: 130,
          child: ListView(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            children: <Widget>[
              headerCategoryItem('iPhone', 'type_phone.png', onPressed: () {}),
              headerCategoryItem('iPad', 'type_ipad.png', onPressed: () {}),
              headerCategoryItem('Macbook', 'type_macbook_air.png',
                  onPressed: () {}),
            ],
          ),
        )
      ],
    );
  }

  Widget headerCategoryItem(String name, String icon, {onPressed}) {
    return Container(
      margin: EdgeInsets.only(left: 15),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: 10),
            width: 86,
            height: 86,
            child: Image.asset(
              'images/$icon',
              width: 35,
              fit: BoxFit.cover,
            ),
            // child: FloatingActionButton(
            //   shape: CircleBorder(),
            //   heroTag: name,
            //   onPressed: onPressed,
            //   backgroundColor: white,
            //   child: Icon(icon, size: 35, color: Colors.black87),
            // )
          ),
          Text(name + ' ›', style: categoryText)
        ],
      ),
    );
  }

  Widget deals(String dealTitle, {onViewMore, List<Widget>? items}) {
    return Container(
      margin: EdgeInsets.only(top: 5),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          sectionHeader(dealTitle, onViewMore: onViewMore),
          SizedBox(
            height: 250,
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: (items != null)
                  ? items
                  : <Widget>[
                      Container(
                        margin: EdgeInsets.only(left: 15),
                        child: Text('No items available at this moment.',
                            style: taglineText),
                      )
                    ],
            ),
          )
        ],
      ),
    );
  }
}
